//
//  NSArray+NSSearchDescriptorSearch.m
//  CloudDoctor
//
//  Created by weida on 15/4/18.
//  Copyright (c) 2015年 ZhongKeYun. All rights reserved.
//

#import "NSArray+NSSearchDescriptorSearch.h"
#import "WS_ChineseToPinyin.h"


@implementation NSArray (NSSearchDescriptorSearch)

/**
 *  @brief  搜索根据一个匹配规则搜索数组，并返回搜索结果
 *
 *  @param descriptor 搜索匹配规则
 *
 *  @return 搜索结果
 */
-(NSArray*) searchArrayUsingDescriptor:(NSSearchDescriptor *)descriptor
{
    NSMutableArray *Result = nil;
    
    /**
     *  @brief  检测参数是否合法
     */
    if ([descriptor isKindOfClass:[NSSearchDescriptor class]])
    {
        if (!Result) {
            Result = [NSMutableArray array];
        }
        
        [Result addObjectsFromArray:[self search:descriptor]];
    }else
    {
        NSLog(@"Must be NSSearchDescriptor");
    }
    
    
    return Result;
}


/**
 *  @brief  搜索根据多个匹配规则搜索数组，并返回搜索结果
 *
 *  @param Descriptors 一个包含搜索规则的数组
 *
 *  @return 搜索结果
 */
-(NSArray *)searchArrayUsingDescriptors:(NSArray *)Descriptors
{
    NSMutableArray *Result = nil;
    
    /**
     *  @brief  检测数组参数是否合法
     */
    for (NSSearchDescriptor *descriptor in Descriptors)
    {
        if ([descriptor isKindOfClass:[NSSearchDescriptor class]])
        {
            if (!Result)
            {
                Result = [NSMutableArray array];
            }
            
            [Result addObjectsFromArray:[self searchArrayUsingDescriptor:descriptor]];
        }else
        {
            NSLog(@"Must be NSSearchDescriptor in Search Descriptors arr...");
        }
    }

    if (!Result.count)
    {
        return Result;
    }
    
    /**
     *  @brief  去除相同的
     */
    NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:Result.count];
    
    for (id model in Result)
    {
        [muArr removeObjectIdenticalTo:model];
        [muArr addObject:model];
    }
    
    return muArr;
}

/**
 *  @brief  使用一条匹配规则进行匹配，并返回匹配成功的数组，如果没有匹配成功，返回nil
 *
 *  @param descriptor 匹配规则描述符
 *
 *  @return 匹配成功返回数组，失败返回nil
 */
-(NSMutableArray *)search:(NSSearchDescriptor *)descriptor
{
    NSMutableArray *Ret = [NSMutableArray array];
    NSString *key = [descriptor valueForKey:@"key"];
    NSString *keyPath = [descriptor valueForKey:@"keyPath"];
    NSArray *keyPaths = [keyPath componentsSeparatedByString:@"."];
    
    if ((!keyPaths.count) || (!key) || ([key isEqualToString:@""])|| ([key isEqual:[NSNull null]]))
    {
        return nil;
    }
   

   
    if (keyPaths.count > 1)
    {//有多级
       

        NSArray *supkeys = [self valueForKeyPath:[keyPath stringByDeletingPathExtension]];
        
        for (NSArray *subs in supkeys)
        {
            if ([subs isKindOfClass:[NSArray class]])
            {
                for (id model in subs)
                {
                    NSString * str = [model valueForKey:keyPaths[keyPaths.count-1]];//取出需要匹配的字段
                    
                    if (![str isKindOfClass:[NSString class]])
                    {//必须是字符串
                        continue;
                    }
                    
                    if ([self MatchKey:key InString:str withDesciptor:descriptor])
                    {
                        [Ret addObject:model];
                    }
                    
                }
            }else
            {
                NSString * str = [subs valueForKey:keyPaths[keyPaths.count-1]];//取出需要匹配的字段
                
                if (![str isKindOfClass:[NSString class]])
                {//必须是字符串
                    continue;
                }
                
                if ([self MatchKey:key InString:str withDesciptor:descriptor])
                {
                    [Ret addObject:subs];
                }
                
                
            }
        }

    }else
    {//只有一级
        
        for (id model in self)
        {
            NSString * str = [model valueForKey:keyPath];//取出需要匹配的字段
            
            if (![str isKindOfClass:[NSString class]])
            {//必须是字符串
                continue;
            }
            
             if ([self MatchKey:key InString:str withDesciptor:descriptor])
            {
                [Ret addObject:model];
            }
            
        }

    }
    
    return Ret;
}

/**
 *  @brief  根据匹配规则对key进行匹配，匹配成功返回YES，失败返回NO
 *
 *  @param key        需要匹配的关键字
 *  @param string     被匹配的字符串
 *  @param descriptor 匹配规则描述符
 *
 *  @return 匹配成功返回YES，失败返回NO
 */
-(BOOL)MatchKey:(NSString *)key  InString:(NSString*)string withDesciptor:(NSSearchDescriptor *)descriptor
{
    BOOL Ret = NO;
    
    if (descriptor.caseSensitivity)
    {
        if ([string rangeOfString:key].length)
        {
            return YES;
        }
        
    }else
    {
        if ([string rangeOfString:key options:NSCaseInsensitiveSearch].length)
        {
            return YES;
        }
    }
    
    if (descriptor.AutoTransfromChineseToPinyin)
    {//支持拼音搜索中文
        NSString *pinyin = [WS_ChineseToPinyin pinyinFromChineseString:string];
        if ([pinyin rangeOfString:key options:NSCaseInsensitiveSearch].length)
        {
            return YES;
        }
    }
    
    return Ret;
}

@end
